package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class Dishontroller {

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据录入的信息保存两张表 一张dish表，一张dishflavor表
     * @param dishDto
     * @return
     */

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        dishService.save(dishDto);

        dishService.saveFlavor(dishDto);

        return R.success("信息录入成功");

    }

    /**
     * 前端分页界面中同时要给出菜品的名称 需要操作
     * @param page
     * @param pageSize
     * @param name
     * @return
     */

    @Transactional
    @GetMapping("/page")
    public R<Page> getPage(Integer page,Integer pageSize,String name){
        Page<Dish> dishPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null, Dish::getName,name);
        dishService.page(dishPage,queryWrapper);

        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = dishDto.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();

            if(categoryName!=null){
                dishDto.setCategoryName(categoryName);
            }
            dishDtoList.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id 回显菜品数据
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishDtoWithFlavor = dishService.getIdWithFlavor(id);

        return R.success(dishDtoWithFlavor);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavorId(dishDto);

        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        String key = "dish_" + dish.getCategoryId()+"status" + dish.getStatus();

        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList !=null){

            return R.success(dishDtoList);

        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId())
                    .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                    .eq(Dish::getStatus,1);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {

            //创建新的实体类来接收不同表格参数
            DishDto dishDto = new DishDto();

            //1.通过工具类拷贝接收dish表格所有参数
            BeanUtils.copyProperties(item, dishDto);

            //2.调用category服务层获取参数CategoryName
            /*LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

            categoryLambdaQueryWrapper.eq(Category::getId, item.getCategoryId());

            Category category = categoryService.getOne(categoryLambdaQueryWrapper);

            dishDto.setCategoryName(category.getName());*/

            //3.调用DishFlavor服务层获取所有该菜品的所有口味列表
            LambdaQueryWrapper<DishFlavor> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

            dishLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());

            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishLambdaQueryWrapper);

            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);

    }

    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids){

        dishService.deleteByIds(ids);

        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> dishStatusByStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);

        List<Dish> list = dishService.list(queryWrapper);
        list.stream().map((item)->{

            item.setStatus(status);

            return item;
        }).collect(Collectors.toList());

        dishService.updateBatchById(list);

        return R.success("状态修改成功");
    }
}
